package com.pentofab.payrollmanagement.ui.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;

import com.pentofab.payrollmanagement.application.PayrollApplicationFactory;
import com.pentofab.payrollmanagement.dao.EmployeeDao;
import com.pentofab.payrollmanagement.dao.model.Company;
import com.pentofab.payrollmanagement.dao.model.UserAccounts;

public class CompaniesListUIController extends AbstractUIController implements
		Initializable {

	@FXML
	Parent root;

	@FXML
	ListView<Company> companiesList;

	
	@FXML
	TextField importFileLoc;
	
	@FXML
	TextField exportFileLoc;
	@FXML
	TextField companyCodes;
	
	UserAccounts logedInUser = null;
	
	ObservableList<Company> companiesListModel;
	EmployeeDao empDao = PayrollApplicationFactory.getEmployeeMgmt();
	
	public void browseImport(){
		
		try{
		FileChooser fileChooser = new FileChooser(); 
        fileChooser.setTitle("Select Company File");

        File file = fileChooser.showOpenDialog(null);
        File destinationFile = new File(file.getAbsolutePath());
        String fileName = destinationFile.getName();
       if(file!=null && !file.isDirectory()){
    	   
    	   importFileLoc.setText(destinationFile.getAbsolutePath());
    	   if(fileName !=null && !fileName.equals(UIMessages.FileName.COMPANY_LIST)){
    		   showError("To import companies, Please select file having name  :"+UIMessages.FileName.COMPANY_LIST);
    		   refreshUI();
    		   return;
    	   }
    	   
    	   
    	   FileReader fr = new FileReader(file);
    	   
    	   BufferedReader br = new BufferedReader(fr);
    	   
    	   String colnms = br.readLine();
    	   if(colnms == null || colnms.equals("")){
    		   
    		   showError("No data in file : "+fileName);
    		   refreshUI();
    		   br.close();
    		   return;
    	   }
    	   
    	   
    	   String[] colArray = colnms.split(",");
    	   if(colArray == null || colArray.length != 12	){
    		   
    		   showError("Improper data in file : "+fileName+", Valid datamust contain only \n"
    		   		+ "Name,Code,Address1,Address2,City,State,Country,ZipCode,Tel1,Tel2,Fax,Email fields");
    		   br.close();
    		   refreshUI();
    		   return;
    	   }
    	   br.close();
    	   
       }else{
    	   showInfo("Export Operation cancelled as file not selected for import.");
    	   refreshUI();
    	   return;
       }
	
		}catch(Exception e){
			refreshUI();
			showError("Error while importing company data.");
		}
	}
	
	public void importSubmit(){
		
		try{

			File file = new File(importFileLoc.getText().trim());
			ArrayList<HashMap<String, String>> companyInfoMap = new ArrayList<HashMap<String,String>>();
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String[] clnmsArray = br.readLine().split(",");
			String dataLine = null;
			while((dataLine = br.readLine()) != null){
				String[] data = dataLine.split(",");

				HashMap<String, String> cur = new HashMap<String, String>();
				for(int i= 0;i < data.length;i++){
					
					cur.put(clnmsArray[i],data[i].replaceAll("'", ""));
				}
				companyInfoMap.add(cur);

			}
			
			System.out.println("companyInfoMap : "+companyInfoMap.size());
			Iterator<HashMap<String, String>> companyInfoMapIterator = companyInfoMap.iterator();
			StringBuffer errorBuffer = new StringBuffer();
			while(companyInfoMapIterator.hasNext()){

				HashMap<String, String > current = companyInfoMapIterator.next();
				try{
					Company company = new Company();
					company.setName(current.get("Name"));
					company.setCompanyID(current.get("Code"));
					company.setAddress1(current.get("Address1"));
					company.setAddress2(current.get("Address2"));
					company.setCity(current.get("City"));
					company.setState(current.get("State"));
					company.setCountry(current.get("Country"));
					company.setZipcode(current.get("ZipCode"));
					company.setTelephone1(current.get("Tel1"));
					company.setTelephone2(current.get("Tel2"));
					company.setFax(current.get("Fax"));
					company.setMailId(current.get("Email"));
					empDao.addCompany(company);
				}catch(Exception e){
					e.printStackTrace();
					errorBuffer.append("Name :"+current.get("Name")+", Code : "+current.get("Code")+"\n");
				}
			}
			
			if(!errorBuffer.toString().equals("")){
				showError("Failed to add following companies due to data error or company with code may already exists.\n"+errorBuffer);
			}
			
			refreshUI();
			br.close();
		}catch(Exception e){
			e.printStackTrace();
			refreshUI();
			showError("Error while importing company data.");
		}
		
	}
	
	public void browseExport(){
		
		
		if(companyCodes.getText().trim().equals("")){
			
			showError("Please select company codes seprated by',' to export.");
			return;
		}
		
		try{
		DirectoryChooser fileChooser = new DirectoryChooser(); 
        fileChooser.setTitle("Select Destination");

        File file = fileChooser.showDialog(null);
        File destinationFile = new File(file.getAbsolutePath());
       if(file!=null && file.isDirectory()){
    	   
    	   exportFileLoc.setText(destinationFile.getAbsolutePath());
    	  
       }else{
    	   showInfo("Export Operation cancelled as Directry nor selected for export.");
    	   refreshUI();
    	   return;
       }
	
		}catch(Exception e){
			refreshUI();
			showError("Error while exporting company data.");
		}
	
	}
	public void exportSubmit(){
		try{
			
			if(companyCodes.getText().trim().equals("")){
				
				showError("Please select company codes seprated by',' to export.");
				return;
			}
			
			String selectedCodes = companyCodes.getText().trim();
			String[] codesArray = selectedCodes.split(",");
			File file = new File(exportFileLoc.getText()+"//"+UIMessages.FileName.COMPANY_LIST);
			FileWriter fw =new FileWriter(file,true);
			BufferedWriter bw =new BufferedWriter(fw);
			bw.write("Name,Code,Address1,Address2,City,State,Country,ZipCode,Tel1,Tel2,Fax,Email\n");
			
			for(int i=0; i < codesArray.length;i++){
				
				Company comp = empDao.getCompany(codesArray[i]);
				StringBuffer dataLine = new StringBuffer();
				dataLine.append(comp.getName()).append(",");
				dataLine.append(comp.getCompanyID()).append(",");
				dataLine.append(comp.getAddress1()).append(",");
				dataLine.append(comp.getAddress2()).append(",");
				dataLine.append(comp.getCity()).append(",");
				dataLine.append(comp.getState()).append(",");
				dataLine.append(comp.getCountry()).append(",");
				dataLine.append(comp.getZipcode()).append(",");
				dataLine.append(comp.getTelephone1()).append(",");
				dataLine.append(comp.getTelephone2()).append(",");
				dataLine.append(comp.getFax()).append(",");
				dataLine.append(comp.getMailId());
				bw.write(dataLine.toString()+"\n");
			}
			
			showInfo("Successfuly exported companies.");
			bw.flush();
			fw.flush();
			bw.close();fw.close();
		}catch(Exception e){
			e.printStackTrace();
			showError("Error while exporting company data.");
		}
		
		
	}
	@Override
	public Parent getView() {
		return root;
	}

	@Override
	public String getTitle() {
		return UIMessages.UITitles.COMPANIES;
	}

	public void add() {
		PayrollApplicationFactory.getMainController().showScreen(
				MainController.ADD_COMPANY_SCREEN, true);
	}

	public void open() {
		Company selectedCompany = CompaniesListUIController.this.companiesList
				.getSelectionModel().getSelectedItem();
		System.out.println("selectedCompany : "+selectedCompany);
		if (selectedCompany == null) {
			showError("Select a company.");
		} else {
			PayrollApplicationFactory
					.getMainController()
					.showScreen(
							MainController.COMPANY_DASH_BOARD_SCREEN,
							true, selectedCompany,logedInUser);
		}
	}
	public void edit() {
		Company selectedCompany = this.companiesList.getSelectionModel()
				.getSelectedItem();
		if (selectedCompany == null) {
			showError("Select a company to edit");
		} else {
			PayrollApplicationFactory.getMainController().showScreen(
					MainController.ADD_COMPANY_SCREEN, true, selectedCompany);
		}
	}

	public void deleteCompany() {
	}

	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
		refreshUI();
		
		this.companiesList.getSelectionModel().selectedItemProperty()
				.addListener(new ChangeListener<Company>() {

					@Override
					public void changed(ObservableValue<? extends Company> ov,
							Company oldSelection, Company newSelection) {
						System.out.println("Seldction "
								+ newSelection.toString());
					}
				});
		this.companiesList.setOnMouseClicked(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent event) {
				if (event.getButton().equals(MouseButton.PRIMARY)) {
					if (event.getClickCount() == 2) {
						Company selectedCompany = CompaniesListUIController.this.companiesList
								.getSelectionModel().getSelectedItem();
						System.out.println("selectedCompany : "+selectedCompany);
						if (selectedCompany == null) {
							showError("Select a company.");
						} else {
							PayrollApplicationFactory
									.getMainController()
									.showScreen(
											MainController.COMPANY_DASH_BOARD_SCREEN,
											true, selectedCompany,logedInUser);
						}
					}
				}
			}
		});
	}

	@Override
	public void refreshUI(Object... args) {
		EmployeeDao empDao = PayrollApplicationFactory.getEmployeeMgmt();
		try {
			List<Company> companies = empDao.getCompanies();
			companiesListModel = FXCollections.observableArrayList();
			companiesListModel.addAll(companies);
			this.companiesList.setItems(companiesListModel);
			
			importFileLoc.clear();exportFileLoc.clear();
			if(args != null && args.length > 0){
				logedInUser = (UserAccounts) args[0];
			}
		} catch (Exception e) {

		}
	}

}
